<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-03-22 20:17:21
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 14:36:06
-->
<template>
  <x-sub-page :isShowBack="false" :content="title" :isFixBtn="true">
    <el-scrollbar class="invoice-info-content" wrap-class="scrollbar-wrapper">
      <!-- 基本信息 -->
      <x-tab :title="$t('financialSynergy.invoice.baseInfo')">
        <el-form :model="params" :rules="rules" ref="params" class="content-form" label-position="top">
          <el-row :gutter="36">
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.supplier')" prop="supplierName">
                <!-- <template #label>
                  <em class="required-icon"> * </em>
                  <span>{{ $t('financialSynergy.invoice.supplier') }}</span>
                </template> -->
                <supplier-select
                  ref="supplier-select"
                  :supplier-id="params.supplierId"
                  :value="params.supplierName"
                  :placeholder="'请选择供应商'"
                  @on-change="handleChangeSupplier"
                >
                </supplier-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.invoiceType')" prop="invoiceType">
                <x-select
                  :placeholder="$t('financialSynergy.invoice.selectPlaceHolder')"
                  v-model="params.invoiceType"
                  :options="dictOptions['srm_invoice.invoice_type']"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.invoiceDate')" prop="invoicingDate">
                <el-date-picker
                  v-model="params.invoicingDate"
                  type="date"
                  :placeholder="$t('financialSynergy.invoice.selectPlaceHolder')"
                  value-format="yyyy-MM-dd"
                  :range-separator="$t('common.to')"
                  :start-placeholder="$t('common.startTime')"
                  :end-placeholder="$t('common.endTime')"
                  default-time="00:00:00"
                  style="width: 100%"
                  :picker-options="pickerOptions"
                  clearable
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.invoiceTitle')" prop="header">
                <!-- <template #label>
                  <em class="required-icon"> * </em>
                  <span>{{ $t('financialSynergy.invoice.invoiceTitle') }}</span>
                </template> -->
                <!-- <el-input
                  v-model="params.header"
                  :placeholder="$t('financialSynergy.invoice.inputPlaceHolder')"
                  clearable
                  maxlength="50"
                ></el-input> -->
                <invoice-select-input
                  :taxId="params.taxId"
                  :value="params.header"
                  :placeholder="'请选择发票抬头'"
                  @on-change="handleChangeInvoice"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.ird')" prop="taxId">
                <el-input
                  v-model="params.taxId"
                  :placeholder="$t('financialSynergy.invoice.autoComplete')"
                  clearable
                  disabled
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.companyPhone')" prop="registrationPhone">
                <el-input
                  v-model="params.registrationPhone"
                  :placeholder="$t('financialSynergy.invoice.autoComplete')"
                  clearable
                  disabled
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.companyAddress')" prop="registrationAddress">
                <el-input
                  v-model="params.registrationAddress"
                  :placeholder="$t('financialSynergy.invoice.autoComplete')"
                  clearable
                  disabled
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.bank')" prop="openingBankName">
                <el-input
                  v-model="params.openingBankName"
                  :placeholder="$t('financialSynergy.invoice.autoComplete')"
                  clearable
                  disabled
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.bankAccount')" prop="openingBankAccount">
                <el-input
                  v-model="params.openingBankAccount"
                  :placeholder="$t('financialSynergy.invoice.autoComplete')"
                  clearable
                  disabled
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.paperTicket')" prop="contacts">
                <el-input
                  v-model="params.contacts"
                  :placeholder="$t('financialSynergy.invoice.inputPlaceHolder')"
                  clearable
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.collectorPhone')" prop="contactsPhone">
                <el-input
                  v-model="params.contactsPhone"
                  :placeholder="$t('financialSynergy.invoice.inputPlaceHolder')"
                  clearable
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.invocieAddress')" prop="invoiceMailingAddress">
                <el-input
                  v-model="params.invoiceMailingAddress"
                  :placeholder="$t('financialSynergy.invoice.inputPlaceHolder')"
                  clearable
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.lectronicInvoiceAddress')" prop="invoiceEmail">
                <el-input
                  v-model="params.invoiceEmail"
                  :placeholder="$t('financialSynergy.invoice.inputPlaceHolder')"
                  clearable
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('financialSynergy.invoice.invocieAmount')" prop="amount">
                <el-input
                  v-model="params.amount"
                  :placeholder="$t('financialSynergy.invoice.autoCount')"
                  clearable
                  disabled
                  maxlength="50"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('financialSynergy.invoice.remark')" prop="remark" class="no-margin-bottom">
                <el-input
                  type="textarea"
                  v-model="params.remark"
                  :placeholder="$t('financialSynergy.invoice.inputPlaceHolder')"
                  clearable
                  maxlength="200"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </x-tab>
      <!-- 对账单明细 -->
      <x-tab :title="$t('financialSynergy.invoice.billsDetail')">
        <div class="bills-btns flex-row">
          <el-button type="primary" @click="handleBillsSource">
            {{ $t('financialSynergy.invoice.billsSource') }}</el-button
          >
          <el-button type="danger" @click="handleBatchDelete"> {{ $t('common.delete') }}</el-button>
        </div>
        <x-table
          ref="tableCom"
          :isPagination="false"
          :data-source="billsList"
          :row-key="'id'"
          :height="300"
          @on-selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="(item, index) in columns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width"
            :min-width="item.minWidth || '-'"
            :label="item.label"
            :sortable="'custom'"
          >
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
            <template #default="scope">
              <more-table-actions :action-list="actions" :row="scope.row" @onActionClick="handleActions" />
            </template>
          </el-table-column>
        </x-table>
      </x-tab>
    </el-scrollbar>
    <source-bills-dialog ref="sourceBillsCom" :other-param="otherParam" @on-submit="getSelectBills" />
    <fixed-btn-area>
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button type="primary" :loading="loading" @click="onSubmit()">
        {{ $t('common.submit') }}
      </el-button>
    </fixed-btn-area>
  </x-sub-page>
</template>
<script>
  import {
    QueryDictMixin,
    checkEmail,
    checkMobilePhone,
    checkFixPhone,
    uniqBy,
    throttle,
    cloneDeep
  } from '@package/utils'
  import SupplierSelect from '@/components/supplier-select/index.vue'
  import { itemColumns as columns, itemAcitons as actions } from '../config/invoiceNotice'
  import SourceBillsDialog from './sourceBillsDialog.vue'
  import { apiPostAddInvoice, apiPutEditInvoice, apiGetInvoice } from '../api/invoiceNotice'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    name: 'AddInvoiceNotice',
    components: {
      SupplierSelect,
      SourceBillsDialog
    },
    mixins: [QueryDictMixin],
    inject: ['closePages'],
    data() {
      return {
        title: '新增',
        columns,
        actions,
        params: {
          supplierName: '',
          supplierId: '',
          invoiceType: '',
          invoicingDate: '',
          header: '',
          taxId: '',
          registrationPhone: '',
          registrationAddress: '',
          openingBankName: '',
          openingBankAccount: '',
          invoiceMailingAddress: '',
          invoiceEmail: '',
          contacts: '',
          contactsPhone: '',
          amount: '',
          remark: '',
          details: []
        },
        rules: {
          invoiceType: [
            {
              required: true,
              message: this.$t('financialSynergy.invoice.selectPlaceHolder'),
              trigger: 'blur'
            }
          ],
          invoicingDate: [
            {
              required: true,
              message: this.$t('financialSynergy.invoice.selectPlaceHolder'),
              trigger: ['blur', 'change']
            }
          ],
          supplierName: [
            {
              required: true,
              message: this.$t('financialSynergy.invoice.supplierHolder'),
              trigger: ['blur', 'change']
            }
          ],
          header: [
            {
              required: true,
              message: this.$t('financialSynergy.invoice.inputPlaceHolder'),
              trigger: ['blur', 'change']
            }
          ],
          contacts: [
            {
              required: false,
              message: this.$t('financialSynergy.invoice.inputPlaceHolder'),
              trigger: 'blur'
            }
          ],
          contactsPhone: [
            {
              required: false,
              message: this.$t('financialSynergy.invoice.inputPlaceHolder'),
              trigger: 'blur'
            },
            { validator: this.validatePhone, trigger: 'blur' }
          ],
          invoiceMailingAddress: [
            {
              required: true,
              message: this.$t('financialSynergy.invoice.inputPlaceHolder'),
              trigger: 'blur'
            }
          ],
          invoiceEmail: [
            {
              required: true,
              message: this.$t('financialSynergy.invoice.inputPlaceHolder'),
              trigger: 'blur'
            },
            { validator: this.validateEmail, trigger: 'blur' }
          ]
        },
        billsList: [],
        selectionRows: [],
        loading: false,
        srmDictKeys: ['srm_invoice.invoice_type', 'srm_invoice.state'],
        pickerOptions: {
          disabledDate: (time) => {
            return new Date(time).getTime() < new Date().getTime() - 86400000
          }
        }
      }
    },
    computed: {
      otherParam() {
        return {
          supplierId: this.params.supplierId || '',
          supplierName: this.params.supplierName || '',
          invoiceState: 0, // 未开票
          state: 3 // 已确认
        }
      }
    },
    created() {
      this.initDictConfig()
      const { query } = this.$route
      if (query?.id) {
        this.getInvoiceDetail(query?.id)
      }
    },
    methods: {
      getInvoiceDetail(id) {
        apiGetInvoice(id).then(({ data }) => {
          this.params = Object.assign(this.params, cloneDeep(data))
          this.billsList = this.params.details
        })
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'delete':
            this.billsList.forEach((item, index) => {
              if (item.id === data.id) {
                this.billsList.splice(index, 1)
              }
            })
            this.params.amount = this.billsList.reduce((arr, total) => {
              return arr + total.totalAmount
            }, 0)
            break
        }
      },
      handleSelectionChange(selectionRows) {
        this.selectionRows = selectionRows
      },
      handleBillsSource() {
        if (!this.params.supplierId) {
          this.$message.error('请选择供应商!')
          return
        }
        this.$refs.sourceBillsCom.handleOpen()
      },
      getSelectBills(list) {
        if (!list?.length) {
          return
        }
        const arr = JSON.parse(
          JSON.stringify(list)
            .replace(/id/g, 'billId')
            .replace(/number/g, 'billNumber')
        )
        const data = [...arr, ...this.billsList]
        this.billsList = uniqBy(data, 'billId')
        this.params.amount = this.billsList.reduce((arr, total) => {
          return arr + total.totalAmount
        }, 0)
      },
      handleBatchDelete() {
        const ids = this.selectionRows.map((v) => v.id)
        if (!ids?.length) {
          this.$message.error(this.$t('financialSynergy.invoice.deleteTips'))
          return
        }
        this.billsList.forEach((item, index) => {
          if (ids.includes(item.id)) {
            this.billsList.splice(index, 1)
          }
        })
        this.params.amount = this.billsList.reduce((arr, total) => {
          return arr + total.totalAmount
        }, 0)
      },
      handleChangeSupplier(val) {
        this.params.supplierName = val.fullName
        this.params.supplierId = val.id
      },
      handleChangeInvoice(val) {
        this.params.header = val.header
        this.params.taxId = val.taxId
        this.params.registrationPhone = val.registrationPhone
        this.params.registrationAddress = val.registrationAddress
        this.params.openingBankName = val.openingBankName
        this.params.openingBankAccount = val.openingBankAccount
      },
      onSubmit: throttle(function () {
        this.loading = true
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            if (!this.billsList?.length) {
              this.$message.error(this.$t('financialSynergy.invoice.billsTips'))
              return
            }
            const param = {
              ...this.params,
              invoicingDate: `${this.params.invoicingDate} 23:59:59`,
              details: this.billsList
            }
            try {
              const { code, msg } = this.params.id ? await apiPutEditInvoice(param) : await apiPostAddInvoice(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.$router.go(-1)
                this.closePages()
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
          }
        })
      }),
      handleClose() {
        this.$confirm(this.$t('common.cancelPrompt'), this.$t('common.tip'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(async () => {
          this.$router.go(-1)
          this.closePages()
        })
      },
      validatePhone(rule, value, callback) {
        if (value && value !== '' && !checkMobilePhone(value) && !checkFixPhone(value)) {
          callback(new Error(this.$t('supplier.registerAudit.pleasePhoneRight')))
        } else {
          callback()
        }
      },
      validateEmail(rule, value, callback) {
        if (value && value !== '' && !checkEmail(value)) {
          callback(new Error(this.$t('financialSynergy.invoice.validateEmailRight')))
        } else {
          callback()
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .required-icon {
    margin-right: 4px;
    color: #f56c6c;
  }
  .no-margin-bottom {
    margin-bottom: 0;
  }
  .bills-btns {
    margin-bottom: 16px;
  }
  ::v-deep .el-scrollbar__wrap {
    // overflow-x: auto;
    overflow-x: hidden;
  }

  ::v-deep .el-scrollbar__view {
    overflow-x: hidden;
  }
  ::v-deep .el-scrollbar__bar.is-horizontal {
    height: 0 !important;
  }
</style>
